//
//  StatusUpdater.m
//  ActiveDeck
//
//  Created by Laura McBride on 8/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "StatusUpdater.h"

int m_PID;
NSString *m_CurrentStatus;
//NSString *m_Channel_ID;
NSDictionary *namespaces;
BOOL isConnected = YES;

@implementation StatusUpdater
@synthesize UpdaterAuthNode, m_initialStatus,loginXML,requestOB,m_Updating,m_CurrentSlide, m_shouldUpdateStatus, upcomingSlideIndex, initialStatusPath, subscriptionPath, channelFormat, m_Channel_ID;

-(id)delegate
{
	return _delegate;
}

-(void)setDelegate:(id)delegate
{
	_delegate = delegate;
}

-(int)GetSlideIndex:(int)SectionID
{
    return [_delegate GetSlideIndexByID:SectionID];
}

-(int)SearchSlideIndex:(int)SectionID
{
    return [_delegate SearchSlideIndex:SectionID];
}

-(void)changeSlide:(NSNumber *)slideIndex
{
    [_delegate changeSlide:slideIndex];
}

-(void)changeSlide:(NSNumber *)slideIndex pageID:(int)pageID
{
    [_delegate changeSlide:slideIndex pageID:pageID];
}

-(void)notifySlideChange{
    [_delegate notifySlideChange];
}

-(void)setUpdateStatus:(BOOL)shouldUpdate{
    m_shouldUpdateStatus = shouldUpdate;
    
    if(shouldUpdate){
        [self performSelectorOnMainThread:@selector(changeSlide:) withObject:upcomingSlideIndex waitUntilDone:NO];
    }
}

-(void)displayNoConnection{
    UIAlertView *alertMSG = [UIAlertView alloc];
    alertMSG = [alertMSG initWithTitle:@"internet Connection Failure"
                               message:@"Please check your Internet connection and try again."
                              delegate:self 
                     cancelButtonTitle:@"OK" 
                     otherButtonTitles:nil];
    
    [alertMSG show];
    [alertMSG release];
}

-(void)initialUpdater:(int)PresentationID loginInfo:(NSString *)loginInfo AuthNode:(GDataXMLElement *)AuthNode initialStatus:(BOOL)initialStatus{
    m_Updating = TRUE;
    loginXML = loginInfo;
    m_PID = PresentationID;
    m_initialStatus = initialStatus;
    m_CurrentSlide = 0;
    UpdaterAuthNode = AuthNode;
    m_shouldUpdateStatus = TRUE;
    
    requestOB = [HttpRequest alloc];
    
    [self performSelectorInBackground:@selector(UpdateStatus) withObject:nil];
}

-(void)initialUpdater:(int)PresentationID
            loginInfo:(NSString *)loginInfo
             AuthNode:(GDataXMLElement *)AuthNode
{
    [self initialUpdater:PresentationID loginInfo:loginInfo AuthNode:AuthNode initialStatus:TRUE];
    
}

-(void)stop
{
    m_Updating = FALSE;
}

#define idleUpdateTime 2

-(void)UpdateStatus
{
    while(m_Updating)
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        
        NSString *status;
        
        if(m_initialStatus)
        {
            m_CurrentStatus = initialStatusPath;
            
            status = [requestOB XML_PostRequest:loginXML
                                      urlString:m_CurrentStatus];  
            
            if ([status isEqualToString:@"-1009"]) {
                if(isConnected){
                    isConnected = NO;
                    
                    [self performSelectorOnMainThread:@selector(displayNoConnection) withObject:nil waitUntilDone:NO];
                }
            } else {
                isConnected = YES;
            }
            
        }
        else
        {
            m_CurrentStatus = subscriptionPath;
            
            status = [requestOB XML_LongPostRequest:UpdaterAuthNode 
                                          urlString:m_CurrentStatus
                                          channelID:m_Channel_ID]; 
            
            if ([status isEqualToString:@"-1009"]) {
                if(isConnected){
                    isConnected = NO;
                    
                    [self performSelectorOnMainThread:@selector(displayNoConnection) withObject:nil waitUntilDone:NO];
                }
            } else {
                isConnected = YES;
            }
        }
        
        if(!m_Updating)
            break;
        
        namespaces = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"http://www.activedeck.com/PowerPoint/", @"ad",
                      nil];
        
        
        NSData *xmlData = [status dataUsingEncoding:NSUTF8StringEncoding];
        NSError *nerr = nil;
        GDataXMLDocument *docXML = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&nerr];
        
        if ([[docXML nodesForXPath:@"//ad:Presentation" namespaces:namespaces error:&nerr] count] > 0)
        {
            GDataXMLElement *PresentationStatus = [[docXML nodesForXPath:@"//ad:Presentation" namespaces:namespaces error:&nerr] objectAtIndex:0];
            int msgID = 0;
            for(GDataXMLElement *msg in [[docXML rootElement] elementsForName:@"Message"])
            {
                if([[[msg attributeForName:@"ID"] stringValue] intValue] > msgID){
                    msgID = [[[msg attributeForName:@"ID"] stringValue] intValue];
                    PresentationStatus = [[msg elementsForName:@"Presentation"] objectAtIndex:0];
                }
            }
            
            [self updateMessageID:PresentationStatus docXML:docXML];
            
            int SlideSection = [[[PresentationStatus attributeForName:@"Section"]stringValue]intValue];	
            
            if(m_CurrentSlide != SlideSection)
            {
                
                NSNumber *SlideIndex = [NSNumber numberWithInt:[self GetSlideIndex:SlideSection]];
                NSLog(@"Changing to Slide Index: %d", SlideSection);
                upcomingSlideIndex = SlideIndex;
                m_CurrentSlide = SlideSection;
                
                if(m_shouldUpdateStatus){           
                    [self performSelectorOnMainThread:@selector(changeSlide:) withObject:SlideIndex waitUntilDone:NO];
                } else {
                    [self performSelectorOnMainThread:@selector(notifySlideChange) withObject:nil waitUntilDone:NO];
                }
            }
        } else if([[[docXML rootElement] elementsForName:@"Message"] count] > 0){
            GDataXMLElement *message = [[[docXML rootElement] elementsForName:@"Message"] objectAtIndex:0];
            
            GDataXMLElement *action = [[message elementsForName:@"Action"] objectAtIndex:0];
            
            if(action){
                if([[[action attributeForName:@"Type"] stringValue] isEqualToString:@"GoTo"]){
                    int section = [[[action attributeForName:@"Section"] stringValue]intValue];
                    int page = [[[action attributeForName:@"Page"] stringValue] intValue];
                    
                    NSNumber *SlideIndex = [NSNumber numberWithInt:[self GetSlideIndex:section]];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self changeSlide:SlideIndex pageID:page]; 
                    });
                }
            } 
            
            GDataXMLElement *userDataMsg = [[message elementsForName:@"UserData"] objectAtIndex:0];
            
            if(userDataMsg){
                NSString *key = [[userDataMsg attributeForName:@"Key"] stringValue];
                NSString *value = [[userDataMsg attributeForName:@"Value"] stringValue];
                
                NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
                [prefs setObject:[NSString stringWithFormat:@"%@", value] forKey:[NSString stringWithFormat:@"Value(%@)",key]];
            }
            
            if(![_delegate getIdleState]){
                GDataXMLElement *idleState = [[message elementsForName:@"Idle"] objectAtIndex:0];
                
                if(idleState){
                    
                    BOOL idleStatus = [[[idleState attributeForName:@"State"] stringValue] boolValue];
                    
                    if(!idleStatus){
                        [_delegate resetIdleTimer];
                    }
                }
            }            
        }
        
        
        
        [docXML release];
        
        [pool release];
    }
    NSLog(@"ExitUpdaterWhileLoop");
}

-(void)updateMessageID:(GDataXMLElement *) PresentationStatus
                docXML:(GDataXMLDocument *)docXML
{
    NSError *nerr = nil;
    
    int messageIndex;
    
    if(m_initialStatus)
    {
        [m_Channel_ID release];
        m_Channel_ID = [[NSString alloc] initWithFormat:@"%@", [[PresentationStatus attributeForName:@"Channel"]stringValue]];
        
        NSLog(@"Channel ID = %@", m_Channel_ID);
        
        messageIndex = [[[PresentationStatus attributeForName:@"MessageID"]stringValue]intValue];
        
        m_initialStatus = FALSE;
    }
    else
    {
        messageIndex = [[docXML nodesForXPath:@"//ad:Message" namespaces:namespaces error:&nerr]count] -1;
        
        
        GDataXMLElement *MessageID;
        MessageID = [[docXML nodesForXPath:@"//ad:Message" namespaces:namespaces error:&nerr] objectAtIndex:messageIndex];
        
        messageIndex = [[[MessageID attributeForName:@"ID"]stringValue]intValue];
        
    }
    
    requestOB.MessageID = messageIndex +1;
}

- (void)dealloc {
    [UpdaterAuthNode release];
    [requestOB release];
    [super dealloc];
}



@end
